package com.itc.bi.mqtt;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itc.bi.entity.MqMqttClientEntity;
import com.itc.bi.service.MqMqttClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @program: itc-airport-cloud
 * @description: mqtt监听
 * @author: songxiude
 * @create: 2024-07-15 15:24
 **/
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {


    @Autowired
    private MqMqttClientService mqttClientService;
    private final AtomicBoolean isInit = new AtomicBoolean(false);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //防止重复触发
        if (!isInit.compareAndSet(false, true)) {
            return;
        }
        //初始化链接mqtt
        try {
            List<MqMqttClientEntity> list = mqttClientService.list(Wrappers.<MqMqttClientEntity>lambdaQuery().eq(MqMqttClientEntity::getEnableFlag,true));
            if(!CollectionUtils.isEmpty(list)){
                for (MqMqttClientEntity mqtt : list) {
                    boolean b = mqttClientService.initMqttServer(mqtt);
                    mqtt.setStatus(1);
                    //设置链接状态
                    if(!b){
                        mqtt.setStatus(0);
                    }
                    mqttClientService.updateById(mqtt);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}